package services

import (
	"errors"
	"hft/Database/admin"
	"hft/global"
)

type AboutCategory struct{}

func (*AboutCategory) Create(data *admin.AboutUsCategory) (err error) {

	res := global.OC_DB.Where("name = ?", data.Name).FirstOrCreate(&data)

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	if res.RowsAffected == 0 {
		return errors.New("该分类已存在")
	}

	return nil
}

func (*AboutCategory) Edit(data *admin.AboutUsCategory) (err error) {

	err = global.OC_DB.Model(&admin.AboutUsCategory{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"sort": data.Sort,
		"name": data.Name,
	}).Error

	if err != nil {
		return errors.New("未知错误")
	}

	return nil

}

func (*AboutCategory) List() (list []*admin.AboutUsCategory, err error) {

	var categoryList []*admin.AboutUsCategory

	global.OC_DB.Find(&categoryList)

	return categoryList, nil

}

func (*AboutCategory) Delete(ids []int) (err error) {

	var list []*admin.AboutUsCategory

	err = global.OC_DB.Find(&list, ids).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	global.OC_DB.Unscoped().Delete(&list)

	return nil

}

var AboutCategoryService = new(AboutCategory)
